package com.tuhui.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;

public class Listener implements Runnable {

    private WatchService watchService;

    public Listener(WatchService watchService) {
            this.watchService = watchService;
    }

    public void run() {
            try {
                while(true){
                    WatchKey watchKey = watchService.take();
                    List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
                    for(WatchEvent<?> event : watchEvents){
                        WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
                        Path path = watchEvent.context();
                        WatchEvent.Kind<Path> kind = watchEvent.kind();
                        //获取路径
                        Path watchable = ((Path) watchKey.watchable()).resolve(watchEvent.context());
                        //创建一个文件夹加入监听
                        if(kind == StandardWatchEventKinds.ENTRY_CREATE){
                            System.out.println("watchable:"+watchable);
                            //如果是一个文件夹加入监听
                            if(Files.isDirectory(watchable)){
                                System.out.println("watchable isDirectory :"+watchable);
                                List<String> pathList = (List<String>) ListenerFile.getDirectorys(watchable.toString());
                                System.out.println("需要监听的文件目录有:"+pathList.size());
                                pathList.forEach(paths->{
                                    Path p = Paths.get(paths);
                                    System.out.println("listener isDirectory :"+paths);
                                    //如果文件下面还有文件则都注册监听
                                    try {
                                        p.register(watchService,StandardWatchEventKinds.ENTRY_CREATE);
                                        //开启一个线程上传当前新建文件夹下的所有文件
                                        ListenerFile.fixedThreadPool.execute(new FtpThread(watchable.toString()));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                            //如果是正常文件则同步文件查看是否写完成了
                            if(Files.isRegularFile(watchable)){
                                //判断文件是否已经写入完成了
                                File file = watchable.toFile();
                                long old_length = 0L;
                                System.out.println("查看文件大小是否一致1: "+old_length + " " + file.length());
                                do{
                                    old_length = file.length();
                                    Thread.sleep(1000);
                                    System.out.println("查看文件大小是否一致2: "+old_length + " " + file.length());
                                }while (old_length!=file.length());
                                System.out.println("文件已写完:"+watchable+"====开始同步文件===========");
                                //上传一个文件
                                ftpUpload(file);
                            }
                        }
                    }
                    watchKey.reset();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                    System.out.println("finally");
            try {
                watchService.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    /**
     * 上传文件时对文件目录进行处理
     * @param file
     */
    public static void ftpUpload(File file){
        String fileName = file.getName();
        FileInputStream in= null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("读取文件流失败");
        }
        //ftp文件保持不变
        String filePath[] = file.getParent().split("\\\\");
        String ftpPath[] = FtpUtil.listenerPath.split("\\\\");
        String uploadFtpPath =  FtpUtil.ftpPath;
        if(filePath.length!=ftpPath.length){
            for(int i=ftpPath.length;i<filePath.length;i++){
                uploadFtpPath+="/"+filePath[i];
            }
        }
        System.out.println("uploadFtpPath:"+uploadFtpPath);
       Boolean upladStatus =  FtpUtil.uploadFile(FtpUtil.ftpHost, FtpUtil.ftpUserName, FtpUtil.ftpPassword, FtpUtil.ftpPort, uploadFtpPath, fileName,in );
        //上传失败记录
        if(!upladStatus){
            FtpUtil.writFile(file.getPath());
        }
    }

}